home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9200 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: apccorp.apcc.com!root
  2. From: nfegan@apcc.com (Noel Fegan)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Help with bizzare bug (Long)
  5. Date: Thu, 29 Feb 1996 10:00:37 GMT
  6. Organization: American Power Conversion
  7. Message-ID: <4h3the$5bb@apccorp.apcc.com>
  8. References: <tday-2702962256130001@tday.slip.netcom.com> <4h19bq$m3m@apccorp.apcc.com>
  9. NNTP-Posting-Host: hewie.galway.apcc.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. nfegan@apcc.com (Noel Fegan) wrote:
  13.  
  14. >tday@netcom.com (Tony Day) wrote:
  15.  
  16. >>   
  17. >>NameAr::NameAr()
  18. >>{ 
  19. >>   name = new char[strlen("Smiley")+1];
  20. >>   name = "Smiley";
  21. >>}     
  22.  
  23. >>
  24. >>NameAr::NameAr(const ArrayDb & a): ArrayDb(a)
  25. >>{
  26. >>   name = new char[strlen("Smiley")+1];
  27. >>   name = "Smiley";
  28.  
  29. >>}     
  30.  
  31. I just looked at you constructors again. I failed to notice that you had in fact
  32. called new correctly to allocate a block of memory for the string, and correctly
  33. adding 1 byte for the '\0' character. Your mistake is an easy one to make, and
  34. is on the next line.
  35.  
  36. name = "Smiley" 
  37.  
  38. This line sets the value of the pointer name to now point to the character array
  39. "Smiley" and does not copy the array to the memory block currently pointed to by
  40. 'name'. This means that the memory block allocate in the previous line becomes
  41. lost and is in effect a memory leak because you have lost you pointer to it, you
  42. no longer have any way of knowing where the block is and it will therefore not
  43. be deleted.
  44.  
  45. You should have used the function strcpy. The line would then read:
  46.  
  47. strcpy(name, "Smiley");
  48.  
  49.  
  50.  
  51. Don't worry easy mistake to make...
  52. --
  53. Noel Fegan
  54. American Power Conversion
  55.  
  56.